package com.thjk.bdf.preloan.service.impl;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.thjk.bdf.common.enmus.AdmissionEnum;
import com.thjk.bdf.common.entity.CheckFailLog;
import com.thjk.bdf.common.entity.MerchantFailLog;
import com.thjk.bdf.common.page.TableDataInfo;
import com.thjk.bdf.common.utils.Constants;
import com.thjk.bdf.common.utils.DateUtils;
import com.thjk.bdf.preloan.service.domain.domainservice.CheckFailLogService;
import com.thjk.bdf.preloan.service.ext.unitygateway.api.InvoiceData;
import com.thjk.bdf.preloan.service.ext.unitygateway.service.InvoiceDataQueryExtService;
import com.thjk.bdf.service.MerchantInfoService;
import com.thjk.bdf.service.response.MerchantInfoRseponse;

/**
 * 
 * @创建日期： 2019年11月1日
 * 
 * @author 束凯
 * @Description：商户相关出列逻辑
 */

@RestController
@RequestMapping("/merchantInfo/")
public class MerchantInfoServiceImpl implements MerchantInfoService {

	private static final Logger logger = LoggerFactory.getLogger(MerchantInfoServiceImpl.class);

	@Autowired
	private InvoiceDataQueryExtService invoiceDataQueryExtService;

	@Autowired
	private CheckFailLogService checkFailLogService;

	/**
	 * 最早开票时间标准
	 */
	@Value("${sj.flow.first.invoice.date.months}")
	private Integer firstInvoiceDateCheck;
	/**
	 * 12个月发票统计额标准
	 */
	@Value("${sj.flow.sum12M.invoice.total}")
	private BigDecimal invoiceTotalSumL12mCheck;

	@RequestMapping(value = "/checkInvoiceFlow", method = RequestMethod.POST)
	@Override
	public MerchantInfoRseponse selectMrtInvoiceFlow(String licenseNo) {

		// 查询数仓接口，并对结果分析
		InvoiceData invoiceData = null;
		MerchantInfoRseponse response = new MerchantInfoRseponse();
		AdmissionEnum result = null;
		try {
			logger.info("开始核查企业发票数据, creditCode:{}", licenseNo);

	        // 1 获取发票流水数据
	        invoiceData = invoiceDataQueryExtService.queryInvoiceData(licenseNo);
	        // 2 校验发票流水数据
	        result = verifyInvoiceData(invoiceData);
	        
			CheckFailLog checkFailLog = buildCheckFailLog(licenseNo, result);
			checkFailLogService.insertCheckFailLog(checkFailLog);

		} catch (Exception e) {
			logger.error("发票流水查询异常", e);
			result = AdmissionEnum.Error_SYS_Code;
		}

		response.setCode(result.getCode());
		response.setMessage(result.getOuterDesc());
		response.setMchtName(invoiceData == null ? null : invoiceData.getMchtName());
		response.setLicenseNo(licenseNo);

		logger.info("白名单企业额度预查, creditCode:{}, resp:{}", licenseNo, response);

		return response;
	}

	/**
	 * 保存不准入信息
	 */
	@RequestMapping(value = "/selectByparams", method = RequestMethod.GET)
	@ResponseBody
	public CheckFailLog buildCheckFailLog(String licenseNo, AdmissionEnum admissionEnum) {
		CheckFailLog checkFailLog = new CheckFailLog();

		checkFailLog.setRegisterNo(licenseNo);
		checkFailLog.setCheckType(Constants.REFUSE_TONGHUA);
		checkFailLog.setResult(AdmissionEnum.getInnerDescByCode(admissionEnum.getCode()));
		checkFailLog.setFailCode(admissionEnum.getCode());

		return checkFailLog;
	}

	@Override
	public TableDataInfo selectByparams(MerchantFailLog merchantInfo) {

		return null;
	}
	
	/**
     * 校验企业发票数据
     *
     * @param invoiceData
     * @return
     */
    private AdmissionEnum verifyInvoiceData(InvoiceData invoiceData) {
        if (null == invoiceData) {
            return AdmissionEnum.Error_1003_1;
        }
        if (!invoiceData.getInitialGetFlag()) {
            return AdmissionEnum.Error_1003_2;
        }
        // 校验最早开票时间
        String firstInvoicedate = invoiceData.getFirstInvoicedate();

        int months = DateUtils.getMonthsBt(DateUtils.parseDate(firstInvoicedate, "yyyy-MM-dd HH:mm:ss"),
                DateUtils.getSysDate());  //月减
        if (months < firstInvoiceDateCheck)
            return AdmissionEnum.Error_1501;
        BigDecimal invoiceTotalSumL12m = invoiceData.getInvoiceTotalSumL12m();
        if(invoiceTotalSumL12m==null||invoiceTotalSumL12m.compareTo(invoiceTotalSumL12mCheck)<0){
        	return AdmissionEnum.Error_1506;
        }

//        // 校验近2个月开票金额都为0
//        List<BigDecimal> invoiceAmtSumL12m = invoiceData.getInvoiceAmtSumL12m();// 最近十四个月开票金额
//        if (null == invoiceAmtSumL12m) {
//            return AdmissionEnum.Error_1506;
//        }
//        if (invoiceAmtSumL12m.size() != 14) {
//            return AdmissionEnum.Error_1506;
//        }
//        // 最近两个月数据等于0
//        if (BigDecimal.ZERO.equals(invoiceAmtSumL12m.get(13))
//                && BigDecimal.ZERO.equals(invoiceAmtSumL12m.get(12))) {
//            return AdmissionEnum.Error_1502;
//        }
//        // 最近14个月内，开票金额为0的月份超过2次（不含本月）
//        int count = 0;
//        for (int i = 0; i < invoiceAmtSumL12m.size(); i++) {
//            if (BigDecimal.ZERO.compareTo((invoiceAmtSumL12m.get(i))) == 0) {
//                count++;
//            }
//        }
//        if (count > 2)
//            return AdmissionEnum.Error_1503;
//
//        // 近12个月流水下降是否超过30%
//        BigDecimal invoiceTotalSumRatio12m = invoiceData.getInvoiceTotalSumRatio12m();
//        if (null == invoiceTotalSumRatio12m) {
//            return AdmissionEnum.Error_1506;
//        }
//        invoiceTotalSumRatio12m = new BigDecimal(100).subtract(
//                invoiceTotalSumRatio12m.multiply(new BigDecimal(100)));
//        if (invoiceTotalSumRatio12m.compareTo(new BigDecimal(30)) > 0)
//            return AdmissionEnum.Error_1504;
//        // 近6个月流水下降是否超过40%
//        BigDecimal invoiceTotalSumRatio6m = invoiceData.getInvoiceTotalSumRatio6m();
//        if (null == invoiceTotalSumRatio6m) {
//            return AdmissionEnum.Error_1506;
//        }
//        invoiceTotalSumRatio6m = new BigDecimal(100).subtract(
//                invoiceTotalSumRatio6m.multiply(new BigDecimal(100)));
//        if (invoiceTotalSumRatio6m.compareTo(new BigDecimal(40)) > 0)
//            return AdmissionEnum.Error_1505;

        return AdmissionEnum.Success_000000;
    }

}
